<div class="mdui-toolbar">
    <button class="mdui-btn mdui-btn-icon" mdui-menu="{target: '#filter-menu'}" id="filter-button"
        mdui-tooltip="{content: '筛选'}">
        <i class="mdui-icon material-icons">filter_list</i>
    </button>
    <div class="mdui-menu" id="filter-menu" style="transform-origin: 100% 0px; position: fixed;">
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">评论/回复 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">用户 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_user_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">帖子 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_post_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">主评论 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_talk_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">搜索</label>
            <input class="mdui-textfield-input" type="text" id='where_search' />
        </div>
    </div>
    <select class="mdui-select" id="sort-select" mdui-select="{position: 'bottom'}">
        <option value="time,0">发布时间 ↑</option>
        <option value="time,1" selected>发布时间 ↓</option>
    </select>
    <div class="mdui-toolbar-spacer"></div>
    <button class="mdui-btn mdui-btn-icon" id="update" mdui-tooltip="{content: '刷新'}">
        <i class="mdui-icon material-icons">refresh</i>
    </button>
</div>
<div id="table"></div>
<div class="mdui-btn-group pages"></div>
<style>
    .ds-table {
        height: calc(100% - 57px - 57px);
        border-top: 1px solid rgba(0, 0, 0, .12);
        border-bottom: 1px solid rgba(0, 0, 0, .12);
    }
</style>
<script>
    !function () {
        var $ = mdui.$;
        var tb = new table.T($("#table"));

        tb.addField("#");
        tb.addField("发送人");
        tb.addField("内容");
        tb.addField("帖子 (ID)");
        tb.addField("主评论 ID");
        tb.addField("发布时间");
        tb.addField("操作");

        var loading = false; // 加载中

        var page = 1; // 当前页
        var size = 1; // 总页数

        var sort_field = 'id'; // 进行排序的字段
        var sort_type = '1'; // 排序方式：0升序1降序

        var where_id = ''; // 筛选数据：用户id
        var where_post_id = ''; // 筛选数据：分区id
        var where_search = ''; // 筛选数据：搜索标题和内容
        var where_user_id = ''; // 筛选数据：用户id
        var where_talk_id = ''; // 筛选数据：主评论id

        $('#update').on('click', update);
        $('#sort-select').on('change', () => {
            var v = $('#sort-select').val();
            sort_field = v.split(',')[0];
            sort_type = v.split(',')[1];
            page = 1;
            update();
        });
        $('#where_id').on('change', () => {
            where_id = $('#where_id').val();
            page = 1;
            update();
        });
        $('#where_post_id').on('change', () => {
            where_post_id = $('#where_post_id').val();
            page = 1;
            update();
        })
        $('#where_search').on('change', () => {
            where_search = $('#where_search').val();
            page = 1;
            update();
        })
        $('#where_user_id').on('change', () => {
            where_user_id = $('#where_user_id').val();
            page = 1;
            update();
        })
        $('#where_talk_id').on('change', () => {
            where_talk_id = $('#where_talk_id').val();
            page = 1;
            update();
        })

        tb.on('cellClick', function ({ row, line }) {
            if ([6].includes(line)) return;
            userDetailed(tb.getCell(row, 0));
        });

        function isFilter() {
            return where_id || where_post_id || where_search || where_user_id;
        }

        function update() {
            if (loading) return;
            loading = true;

            $('#filter-button')[isFilter() ? 'addClass' : 'removeClass']('mdui-text-color-theme')

            renderPages();
            tb.clear();
            tb.startLoading();

            $.ajax({
                url: "./api/get_talk_list?p=" + page +
                    '&sort_field=' + encodeURIComponent(sort_field) +
                    '&sort_type=' + encodeURIComponent(sort_type) +
                    '&where_id=' + encodeURIComponent(where_id) +
                    '&where_post_id=' + encodeURIComponent(where_post_id) +
                    '&where_user_id=' + encodeURIComponent(where_user_id) +
                    '&where_talk_id=' + encodeURIComponent(where_talk_id) +
                    '&where_search=' + encodeURIComponent(where_search),
                dataType: "json",
                success: function (res) {
                    if (res.code == 200) {
                        tb.endLoading();
                        loading = false;

                        size = res.data.size;

                        if (size) {
                            $('.pages').show();
                            var data = res.data.data
                            for (let d of data) {
                                let name_ = $(`<div class="mdui-chip">
  <img class="mdui-chip-icon" src="avatar1.jpg"/>
  <span class="mdui-chip-title">Example Chip</span>
</div>`);
                                name_.find('img').attr('src', d.user_img);
                                name_.find('span').text(d.user_name);

                                let newtab = $(`<a class="mdui-btn mdui-btn-icon" target="_blank" mdui-tooltip="{content: '打开帖子'}"><i class="mdui-icon material-icons">open_in_new</i></a>`)
                                let change = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '更改'}"><i class="mdui-icon material-icons">create</i></button>`)
                                let remove = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '删除'}"><i class="mdui-icon material-icons">delete</i></button>`)


                                newtab.attr('href', '/post/' + d.id);

                                change.on('click', function () {
                                    changePage(d.id);
                                })

                                remove.on('click', function () {
                                    removeTalk(d.id);
                                })


                                tb.addRow([
                                    d.id,
                                    {
                                        type: "el",
                                        el: name_
                                    },
                                    d.text,
                                    d.post_id ? `${d.post_title} (${d.post_id})` : '-',
                                    d.talk_id || '-',
                                    new Date(d.time * 1000).toLocaleString(),
                                    {
                                        type: 'el',
                                        el: $('<div></div>').append(newtab).append(change).append(remove)
                                    }
                                ]);
                            }
                        } else {
                            $('.pages').hide();
                        }
                        renderPages();
                    }
                    else {
                        mdui.snackbar(res.msg || "加载失败")
                    }
                }
            });
        }

        function renderPages() {
            $(".pages").html('');
            var omit = true; // 是否省略

            // 添加向左翻页按钮
            var left = $(`<button class="mdui-btn left">&lt;</button>`)
            left.appendTo($(".pages"));

            for (let i = 0; i < size; i++) {
                let toadd = false; // 是否要添加页数按钮

                if (i === 0) toadd = true; // 第一页要添加
                if (i === size - 1) toadd = true; // 最后一页要添加
                if (i - page < 2 && i - page > -4) toadd = true; // 如果与当前页的距离小于2，则添加
                if (page < 5 && i < 7) toadd = true; // 如果当前页小于5，则前7页都要添加
                if (page > size - 5 && i > size - 7) toadd = true; // 如果当前页在倒数5页范围内，则倒数7页都要添加

                if (toadd) {
                    // 渲染页数按钮
                    let button = $(`<button class="mdui-btn ${(i + 1) == page ? `mdui-btn-active` : ""} page-num">${i + 1}</button>`);
                    button.on("click", () => { // 点击事件
                        page = Number(i + 1);
                        update();
                    })
                    button.appendTo($(".pages"));
                    omit = true;
                } else {
                    if (omit) {
                        $(`<button class="mdui-btn" disabled>...</button>`).appendTo($(".pages"));
                        omit = false;
                    }
                }
            }

            // 添加向右翻页按钮
            var right = $(`<button class="mdui-btn right">&gt;</button>`)
            right.appendTo($(".pages"));

            // 根据条件禁用按钮
            left.prop("disabled", page === 1);
            right.prop("disabled", page === size)

            // 添加点击事件
            left.on("click", () => { // 向左
                page -= 1
                update();
            })

            right.on("click", () => { // 向右
                page += 1
                update();
            })
        }

        function userDetailed(id) {
            const dialog = $.dialog({
                history: false,
                cssClass: "ds-user-detailed ds-loadable",
                content: `
<p class='mdui-typo-subheading'>基本信息</p>
<table class="mdui-table mdui-shadow-0" id='ds-ud-basic'></table>

<div class="mdui-spinner"></div>
`
            });

            const content = dialog.$element

            window.parent.mdui.mutation();

            $.ajax({
                url: "./api/get_talk_info?id=" + id,
                dataType: "json",
                success: function (res) {
                    if (res.code != 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败")
                    }

                    const data = res.data;

                    content.find('.mdui-spinner').remove();

                    // 信息表
                    const tableData = {
                        "#ds-ud-basic": [
                            ['评论 ID', data.id],
                            ['评论内容', data.text],
                            ['发送者 ID', data.user_id],
                            ['发送者 昵称', data.user_name],
                            ['帖子 ID', data.post_id || '-'],
                            ['帖子 名称', data.post_title || '-'],
                            ['主评论 ID', data.talk_id || '-'],
                            ['发送时间', new Date(data.time * 1000).toLocaleString()],
                            ['发送者 ip', data.ip],
                        ],
                    };


                    for (let k in tableData) {
                        let table = content.find(k);

                        for (let i = 0; i < tableData[k].length; i++) {
                            let tr = $(`<tr></tr>`);

                            for (let j = 0; j < tableData[k][i].length; j++) {
                                let td = $(`<td></td>`);

                                td.text(tableData[k][i][j]);
                                tr.append(td);
                            }

                            table.append(tr);
                        }
                    }


                    dialog.handleUpdate();
                }
            });
        }

        function changeApi(id, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: "./api/change_talk_info",
                    method: 'POST',
                    data: {
                        id: id,
                        ...data
                    },
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 200) {
                            resolve()
                        } else {
                            reject(res.msg)
                        }
                    },
                    error: function (res) {
                        reject(res.msg)
                    }
                });
            })
        };

        function changePage(id) {
            var saving = false;

            const dialog = $.dialog({
                history: false,
                cssClass: "ds-loadable",
                content: `
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">内容</label>
            <textarea  class="mdui-textfield-input" type="text" id='ds-change-text' maxlength="100000" required ></textarea>
      <div class="mdui-textfield-error">内容不能为空</div>
        </div>
<div class="mdui-spinner"></div>`,
                buttons: [{
                    text: '取消',
                    close: false,
                    onClick() {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        dialog.close();
                    }
                }, {
                    text: '保存',
                    close: false,
                    onClick: function () {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        const text = content.find('#ds-change-text').val();

                        content.find('input,a,select').attr('disabled', '');
                        saving = true;
                        changeApi(id, {
                            text
                        }).then(() => {
                            dialog.close();
                            update();
                            saving = false;
                            return mdui.snackbar("修改成功")
                        }, (msg) => {
                            saving = false;
                            content.find('input,a,select').removeAttr('disabled');
                            return window.parent.mdui.snackbar(msg || "修改失败")
                        });
                    },
                }]
            });

            const content = dialog.$element

            window.parent.mdui.mutation();

            $.ajax({
                url: "./api/get_talk_info?id=" + id,
                dataType: "json",
                success: function (res) {
                    if (res.code != 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败")
                    }

                    const data = res.data;
                    content.find('#ds-change-text').val(data.text);

                    window.parent.mdui.updateTextFields();
                    window.parent.mdui.mutation();

                    content.find('.mdui-spinner').remove();
                    dialog.handleUpdate();

                }
            });
        }

        function removeTalk(id) {
            mdui.$.confirm('确定要删除这条评论吗？如果该评论有回复，会被一起删除！', '确认删除', function () {
                $.ajax({
                    url: './api/delete_talk',
                    method: 'POST',
                    data: { id: id },
                    success: function (response) {
                        const res = JSON.parse(response);
                        if (res.code === 200) {
                            window.parent.mdui.snackbar("删除成功")
                            update();
                        } else {
                            window.parent.mdui.snackbar(res.msg || "删除失败");
                        }
                    }
                });
            });

        }

        update();
    }();
</script>